package client.gui.util;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.DefaultListModel;
import javax.swing.ListModel;
import javax.swing.SwingUtilities;

import client.TcpClient;

import util.ClientProtocol;
import util.MessageCreator;

public class GUIChanger {
	
	private DefaultListModel<String> infoModel = new DefaultListModel<String>();
	private DefaultListModel<String> orderModel = new DefaultListModel<String>();
	private Map<String,String> orderReferences = new HashMap<>();
	TcpClient tc;
	
	public GUIChanger(TcpClient tc) {
		this.tc = tc;
	}


	public void update(final String msg) {
		SwingUtilities.invokeLater( new Runnable() {
			@Override
			public void run() {
				infoModel.addElement(msg);
				if(msg.matches(ClientProtocol.NEW_ORDER_OK_MATCHER)) {
					Pattern pattern = Pattern.compile(ClientProtocol.NEW_ORDER_OK_MATCHER);
					Matcher matcher = pattern.matcher(msg);
					while(matcher.find()) {
						orderModel.addElement(MessageCreator.orderModelElement(matcher.group(2),Integer.parseInt(matcher.group(6))));
						orderReferences.put(matcher.group(2), MessageCreator.orderModelElement(matcher.group(2),Integer.parseInt(matcher.group(6))));
					}
				} else if(msg.matches(ClientProtocol.MATCH_ORDER_MATCHER)) {
					Pattern pattern = Pattern.compile(ClientProtocol.MATCH_ORDER_MATCHER);
					final Matcher matcher = pattern.matcher(msg);
					while(matcher.find()) {
						orderModel.removeElement(MessageCreator.orderModelElement(matcher.group(2), (Integer.parseInt(matcher.group(5)) + Integer.parseInt(matcher.group(6)))));	
						if(matcher.group(4).equals("P")) {
							orderModel.addElement(MessageCreator.orderModelElement(matcher.group(2),Integer.parseInt(matcher.group(6))));
							orderReferences.put(matcher.group(2),MessageCreator.orderModelElement(matcher.group(2),Integer.parseInt(matcher.group(6))));
						} else {
							orderReferences.remove(matcher.group(2));
						}
					}
				} else if(msg.matches(ClientProtocol.CANCEL_ORDER_DONE_MATCHER)) {
					Pattern pattern = Pattern.compile(ClientProtocol.CANCEL_ORDER_DONE_MATCHER);
					final Matcher matcher = pattern.matcher(msg);
					while(matcher.find()) {
						orderModel.removeElement(orderReferences.get(matcher.group(2)));	
					}
				} else if(msg.matches(ClientProtocol.FAREWELL_MATCHER)) {
					tc.disconnect();
				}
			}
		});
	}

	public ListModel<String> getListModel() {
		return infoModel;
	}
	
	public DefaultListModel<String> getOrderModel() {
		return orderModel;
	}
	
}
